﻿package com.bookstore.admin.products.handler;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.bookstore.admin.products.service.IAdminProductService;
import com.bookstore.commons.beans.Product;
import com.bookstore.commons.beans.ProductList;
import com.bookstore.commons.vo.AdminProduct;
import com.bookstore.utils.PageModel;

@Controller
@RequestMapping("/admin/products")
public class AdminProductHandler {

	@Autowired
	private IAdminProductService  adminProductService;
	
	@RequestMapping("/listProduct.do")
	public String listProduct(AdminProduct condition,@RequestParam(defaultValue="1")Integer pageIndex,Model model) {
		
		System.out.println("condition +"+ condition);
		PageModel pageModel = new  PageModel();
		pageModel.setPageIndex(pageIndex);
		int count = adminProductService.findCountByManyCondition(condition);
		
		pageModel.setRecordCount(count);
		List<Product> products = adminProductService.findProductsByManyConfition(condition,pageModel);
		model.addAttribute("condition",condition );
		model.addAttribute("pageModel",pageModel );
		model.addAttribute("products",products );
		return "/admin/products/list.jsp";
	}
	
	@RequestMapping("/findProductById.do")
	public String findProductById(String id,Model model) {
		Product product = adminProductService.findProductById(id);
		model.addAttribute("p", product);
		System.out.println(product);
		return "/admin/products/edit.jsp";
	}
	
	@RequestMapping("/updateProduct.do")
	public String updateProduct(Product product,MultipartFile upload,HttpSession session,Model model) throws IOException {
		
		
		if(upload != null) {
			String path = session.getServletContext().getRealPath("/upload");
			Product target = adminProductService.findProductById(product.getId());
			File targetFile = new File(path,target.getImgurl());
			if(targetFile.exists()) {
				targetFile.delete();
			}
			String fileName = UUID.randomUUID()+ upload.getOriginalFilename();
			upload.transferTo(new File(path+fileName));
			product.setImgurl(path+fileName);
		}
		int rows = adminProductService.modifyProductById(product);
		
		if(rows > 0) {
			return "redirect:/admin/products/listProduct.do";
			
		}else {
			model.addAttribute("msg", "修改信息失败！");
			return "";
		}
		
	}
	
	@RequestMapping("/addProduct.do")
	public String addProduct(Product product,MultipartFile upload,HttpSession session,Model model) throws IllegalStateException, IOException {
		String path = session.getServletContext().getRealPath("/upload");
		File file = new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		String fileName = UUID.randomUUID()+upload.getOriginalFilename();
		upload.transferTo(new File(path+File.separator+fileName));
		product.setImgurl(path+fileName);
		int rows = adminProductService.addProduct(product);		
		if(rows > 0) {
			return "redirect:/admin/products/listProduct.do";
		}else {
			model.addAttribute("msg", "添加商品失败！");
			return "/admin/products/error.jsp";
		}
	}
	
	@RequestMapping("/removeProduct.do")
	public String removeProduct(String id,String imgurl,Model model,HttpSession session) {
		
		String path = session.getServletContext().getRealPath("/upload");
		File targetFile = new File(path,imgurl);
		if(targetFile.exists()) {
			targetFile.delete();
		}
		int rows = adminProductService.removeProductById(id);
		
		
		if(rows > 0) {
			return "redirect:/admin/products/listProduct.do";
		}else {
			model.addAttribute("msg", "删除商品失败！");
			return "/admin/products/error.jsp";
		}
	}
	
	@RequestMapping("/download.do")
	public void downloadProduct(String year ,String month,HttpServletResponse response,HttpSession session,HttpServletRequest request) throws IOException{

			List<ProductList> productList =   adminProductService.findProductList(year,month);
		
			String monthName,yearName ;
			if("0".equals(month)) {
				monthName = "总销售榜单" ;
			}else {
				monthName =  month + "月销售榜单";
			}
			if("".equals(year)) {
				yearName = "2018年";
			}else {
				yearName = year + "年";
			}
		
		
		String fileName = yearName + "_"+monthName+".lsx";
		String sheetName = monthName ;
		String titleName = yearName +"年"+month ;
		String[] tableHead = {"商品名称","商品销量"};
		
		int columnNum = 2;
		String[][] dataList = new String[productList.size()][columnNum];
		for(int i = 0;i < productList.size();i++){
			ProductList pl = productList.get(i);
		
			dataList[i][0] = pl.getName();
			dataList[i][1] = pl.getSalnum();
			
		}
		
		//对应的excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		//在wb中创建一个sheet
		HSSFSheet sheet =  wb.createSheet(sheetName);
		//创建第一行
		HSSFRow row1 = sheet.createRow(0);
		//创建第一行的第一个单元格
		HSSFCell cell1 = row1.createCell(0);
		//合并第一行的单元格
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
		//给第一行第一个单元格添加内容
		cell1.setCellValue(titleName);
		
		//创建第二行
		HSSFRow row = sheet.createRow(1);
		for(int i = 0; i < columnNum; i++){
			row.createCell(i).setCellValue(tableHead[i]);
		}
		
		//创建内容行
		for(int i = 0;i < productList.size();i++){
			row = sheet.createRow(i+2);
			for (int j = 0; j < columnNum; j++) {
				row.createCell(j).setCellValue(dataList[i][j]);
			}
			
		}
		
		//wb写入字节流
		OutputStream out = response.getOutputStream();
		wb.write(out);
		//excel文件下载
		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+processFileName(request, fileName));
		
		
		/*
		 * 
		 * CSV 文件存储
		List<ProductList> productList =  adminProductService.findProductList(year,month);
		String filename = year +"_"+month+"_"+"销售表单.csv";
		filename = processFileName(request, filename);
		response.setContentType(session.getServletContext().getMimeType(filename));
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		response.setCharacterEncoding("gbk");
		
		PrintWriter out= response.getWriter();
		out.println("商品名称"+","+"商品销量");
		for(ProductList p :productList){
			out.println(p.getName()+","+p.getSalnum());
		}
		//刷新缓存区，以便缓存区不满时不会显示里边的内容
		out.flush();
		//关闭缓存区
		out.close();*/
	}
	
	static String processFileName(HttpServletRequest request,String fileName){
		
		String codeFileName = null;
	try{
		
		if (request.getHeader("user-agent").toLowerCase().contains("msie")) {  
	        // IE  
			codeFileName = URLEncoder.encode(fileName, "UTF-8");  
		} else {  
		       // 非IE  
			codeFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
		}  
		
	}catch(Exception e){
		e.printStackTrace();
	}
	
		return codeFileName;
	
}
	
}
